package tech.aistar.controller;


import com.fasterxml.jackson.databind.util.ObjectBuffer;
import co.elastic.clients.elasticsearch._types.query_dsl.QueryBuilders;
import com.github.pagehelper.PageInfo;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.elasticsearch.client.elc.ElasticsearchTemplate;
import org.springframework.data.elasticsearch.client.elc.NativeQueryBuilder;
import org.springframework.data.elasticsearch.client.erhlc.ElasticsearchRestTemplate;
import org.springframework.data.elasticsearch.client.erhlc.NativeSearchQueryBuilder;
import org.springframework.data.elasticsearch.core.SearchHits;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import tech.aistar.pojo.SongList;
import tech.aistar.pojo.SongListIndex;
import tech.aistar.service.SongListService;
import tech.aistar.vo.Result;

import javax.naming.directory.SearchResult;
import java.io.IOException;
import java.util.*;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@RestController
@RequestMapping("song")
public class SongController {
    @Autowired
    private SongListService songListService;

    @Autowired
    private ElasticsearchTemplate elasticsearchTemplate;
    //搜索引擎
//    @GetMapping("search1/{titles}/{curr}/{limit}")
//    public ResponseEntity<List<SongListIndex>> search(HttpServletRequest request,@PathVariable("titles") String titles, @PathVariable("curr") String curr,@PathVariable("limit") String limit) {
//        PageInfo<SongList> pageInfo = songListService.finds(titles,Integer.valueOf(curr),Integer.valueOf(limit));
//        QueryBuilder queryBuilder = QueryBuilders.matchQuery("titles", titles);
//
//        SearchQuery searchQuery = new NativeSearchQueryBuilder()
//                .withQuery(queryBuilder)
//                .withHighlightFields(new HighlightBuilder.Field("title").preTags("<em>").postTags("</em>"))
//                .build();
//
//        List<SongListIndex> result = elasticsearchTemplate.queryForList(searchQuery, SongListIndex.class);
//        return ResponseEntity.ok(result);
//    }
    @Autowired
    private RedisTemplate redisTemplate;
//    @GetMapping("search/{singerid}")
//    public Result Songsearch(@RequestParam("songTitle") String songTitle){
//        List<SongList> songLists=songListService.findAll(songTitle);
//        System.out.println(songLists);
//        if (songLists==null){
//            return new Result("404","歌名不存在!");
//        }
//        else {
//            return new Result("202","查询成功!");
//        }


//    }
    @GetMapping("select")
    public Result songselect(HttpServletResponse resp){
        resp.setContentType("application/json;charset=utf-8");
        List<SongList> songLists=songListService.Allfind();

        return new Result("200","查询成功",songLists);
    }
        @GetMapping("search/{titles}/{curr}/{limit}")
        public Result index(HttpServletRequest request,@PathVariable("titles") String titles, @PathVariable("curr") String curr,@PathVariable("limit") String limit){

            //处理一下title为null的场景
//            titles = titles==null?"":titles;
//            System.out.println(titles+"jjjjjjjjjjjjj");
            PageInfo<SongList> pageInfo = songListService.finds(titles,Integer.valueOf(curr),Integer.valueOf(limit));

            //放入到request作用域中
            //为了让搜索的关键字能够回显到页面
            request.setAttribute("titles",titles);
            ValueOperations vop = redisTemplate.opsForValue();
            vop.set("titles",titles);

            return new Result("200","查询成功",pageInfo);
        }


    @GetMapping("list/{name}")//用name拿到歌手的歌曲
    public Result songList(@PathVariable ("name") String name)throws IOException {

        List<SongList> songLists=songListService.getBySingerName(name);
        return new Result("200","查询成功",songLists);
    }

    @GetMapping("lyrics/{id}")
    public Result songLyrics(@PathVariable ("id") Integer id)throws IOException {
       SongList song= songListService.getBySongI(id);
        return new Result("200","查询成功",song);
    }

    @GetMapping("bofang/{id}")
    public Result songbo(@PathVariable ("id") String id)
    {
        List<SongList> songLists=songListService.getBySongId(Integer.valueOf(id));
        return new Result("200","查询成功",songLists);
    }
    @GetMapping("danbofang/{songListId}")
    public Result setGedant(@PathVariable("songListId") String songListId)
    {
        List<SongList> list=songListService.findAlllist(Integer.valueOf(songListId));
        return new Result("200","查询成功",list);

    }
    @GetMapping("danbofang1/{songListId1}")
    public Result setGedant1(@PathVariable("songListId1") String songListId1)
    {
        List<SongList> list=songListService.findAlllist1(Integer.valueOf(songListId1));
        return new Result("200","查询成功",list);

    }

//    @GetMapping("all")
//    public Result all(@PathVariable SongList songList)
//    {
//        List<SongList> songLists=songListService.Allfind();
//        return new Result("200","查询成功",songLists);
//    }

    @GetMapping("hot")
    public Result hotSong(HttpServletRequest request){
        List<SongList> songLists=songListService.hotSong();
        for (SongList list : songLists) {
            Integer id=list.getId();
            String tit=list.getSongTitle();
            Map<Integer,String> map=new HashMap<>();
            map.put(id,tit);
            Integer click= list.getClicks();
           redisTemplate.opsForZSet().add("hotSong",map,click);
        }
        Set<String> set=  redisTemplate.opsForZSet().reverseRange("hotSong",0,32);
        List<String> ls=new ArrayList<>(set);
//        System.out.println(ls);
        return new Result("200","查询出来了",ls);
    }
}
